const express = require('express');
const router = express.Router();
const Food = require('../models/Food');

// 获取所有食物
router.get('/', async (req, res) => {
  try {
    const foods = await Food.getAllFoods();
    res.json({
      success: true,
      data: foods,
      total: foods.length
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取食物列表失败',
      error: error.message
    });
  }
});

// 根据冰箱ID获取食物
router.get('/refrigerator/:refrigeratorId', async (req, res) => {
  try {
    const { refrigeratorId } = req.params;
    const foods = await Food.getFoodsByRefrigerator(refrigeratorId);
    res.json({
      success: true,
      data: foods,
      total: foods.length
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '根据冰箱获取食物失败',
      error: error.message
    });
  }
});

// 根据温度状态获取食物（支持多选）
router.get('/temperature/:temperatureStatus', async (req, res) => {
  try {
    const { temperatureStatus } = req.params;
    
    // 支持多个温度状态，用逗号分隔
    const temperatureStatuses = temperatureStatus.split(',').map(s => s.trim());
    
    // 验证温度状态是否有效
    const validStatuses = ['room_temp', 'refrigerated', 'frozen'];
    const invalidStatuses = temperatureStatuses.filter(status => !validStatuses.includes(status));
    
    if (invalidStatuses.length > 0) {
      return res.status(400).json({
        success: false,
        message: `无效的温度状态: ${invalidStatuses.join(', ')}`,
        validStatuses: validStatuses
      });
    }
    
    const foods = await Food.getFoodsByTemperature(temperatureStatuses);
    res.json({
      success: true,
      data: foods,
      total: foods.length,
      temperatureStatuses: temperatureStatuses
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '根据温度状态获取食物失败',
      error: error.message
    });
  }
});

// 根据冰箱ID和温度状态获取食物（支持组合查询）
router.get('/filter', async (req, res) => {
  try {
    const { refrigerator_id, temperature_status } = req.query;
    
    // 处理温度状态参数，如果未传则默认所有温度状态
    let temperatureStatuses = null;
    if (temperature_status) {
      temperatureStatuses = temperature_status.split(',').map(s => s.trim());
      
      // 验证温度状态是否有效
      const validStatuses = ['room_temp', 'refrigerated', 'frozen'];
      const invalidStatuses = temperatureStatuses.filter(status => !validStatuses.includes(status));
      
      if (invalidStatuses.length > 0) {
        return res.status(400).json({
          success: false,
          message: `无效的温度状态: ${invalidStatuses.join(', ')}`,
          validStatuses: validStatuses
        });
      }
    }
    // 如果没有传温度状态，默认为所有状态
    else {
      temperatureStatuses = ['room_temp', 'refrigerated', 'frozen'];
    }
    
    // 调用模型方法
    const foods = await Food.getFoodsByRefrigeratorAndTemperature({
      refrigeratorId: refrigerator_id ? parseInt(refrigerator_id) : null,
      temperatureStatuses: temperatureStatuses
    });
    
    res.json({
      success: true,
      data: foods,
      total: foods.length,
      filters: {
        refrigerator_id: refrigerator_id || '所有冰箱',
        temperature_statuses: temperature_status ? temperatureStatuses : '所有温度状态'
      },
      description: {
        refrigerator_filter: refrigerator_id ? `冰箱ID: ${refrigerator_id}` : '所有冰箱',
        temperature_filter: temperature_status ? `温度状态: ${temperatureStatuses.join(', ')}` : '所有温度状态'
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '根据条件获取食物失败',
      error: error.message
    });
  }
});

// 获取即将过期的食物
router.get('/expiring/:days?', async (req, res) => {
  try {
    const days = parseInt(req.params.days) || 3;
    const foods = await Food.getExpiringFoods(days);
    res.json({
      success: true,
      data: foods,
      total: foods.length,
      message: `获取${days}天内即将过期的食物`
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取即将过期食物失败',
      error: error.message
    });
  }
});

// 获取已过期的食物
router.get('/expired', async (req, res) => {
  try {
    const foods = await Food.getExpiredFoods();
    res.json({
      success: true,
      data: foods,
      total: foods.length
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取已过期食物失败',
      error: error.message
    });
  }
});

// 获取需要提醒的食物
router.get('/reminders', async (req, res) => {
  try {
    const foods = await Food.getFoodsNeedingReminder();
    res.json({
      success: true,
      data: foods,
      total: foods.length
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取需要提醒的食物失败',
      error: error.message
    });
  }
});

// 根据ID获取食物详情
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const food = await Food.getFoodById(id);
    
    if (!food) {
      return res.status(404).json({
        success: false,
        message: '食物不存在'
      });
    }

    res.json({
      success: true,
      data: food
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取食物详情失败',
      error: error.message
    });
  }
});

// 搜索食物
router.get('/search/:keyword', async (req, res) => {
  try {
    const { keyword } = req.params;
    const foods = await Food.searchFoods(keyword);
    res.json({
      success: true,
      data: foods,
      total: foods.length
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '搜索食物失败',
      error: error.message
    });
  }
});

// 创建食物
router.post('/', async (req, res) => {
  try {
    const foodData = req.body;
    
    // 验证必填字段
    if (!foodData.put_in_date || !foodData.shelf_life_days || !foodData.expiry_date || 
        !foodData.temperature_status || !foodData.template_id || !foodData.refrigerator_id) {
      return res.status(400).json({
        success: false,
        message: '放入时间、保质期、截止时间、温度状态、模板ID和冰箱ID为必填字段'
      });
    }

    const food = await Food.createFood(foodData);
    res.status(201).json({
      success: true,
      message: '食物创建成功',
      data: food
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '创建食物失败',
      error: error.message
    });
  }
});

// 批量创建食物
router.post('/batch', async (req, res) => {
  try {
    const { foods } = req.body;
    
    if (!Array.isArray(foods) || foods.length === 0) {
      return res.status(400).json({
        success: false,
        message: '请提供有效的食物列表'
      });
    }

    // 验证每个食物的必填字段
    for (const foodData of foods) {
      if (!foodData.put_in_date || !foodData.shelf_life_days || !foodData.expiry_date || 
          !foodData.temperature_status || !foodData.template_id || !foodData.refrigerator_id) {
        return res.status(400).json({
          success: false,
          message: '每个食物的放入时间、保质期、截止时间、温度状态、模板ID和冰箱ID为必填字段'
        });
      }
    }

    const createdFoods = await Food.batchCreateFoods(foods);
    res.status(201).json({
      success: true,
      message: `成功批量创建${createdFoods.length}个食物`,
      data: createdFoods
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '批量创建食物失败',
      error: error.message
    });
  }
});

// 更新食物
router.put('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const foodData = req.body;
    
    // 验证必填字段
    if (!foodData.put_in_date || !foodData.shelf_life_days || !foodData.expiry_date || 
        !foodData.temperature_status || !foodData.template_id || !foodData.refrigerator_id) {
      return res.status(400).json({
        success: false,
        message: '放入时间、保质期、截止时间、温度状态、模板ID和冰箱ID为必填字段'
      });
    }

    const food = await Food.updateFood(id, foodData);
    if (!food) {
      return res.status(404).json({
        success: false,
        message: '食物不存在'
      });
    }

    res.json({
      success: true,
      message: '食物更新成功',
      data: food
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '更新食物失败',
      error: error.message
    });
  }
});

// 移动食物到其他冰箱
router.put('/:id/move', async (req, res) => {
  try {
    const { id } = req.params;
    const { refrigerator_id } = req.body;
    
    if (!refrigerator_id) {
      return res.status(400).json({
        success: false,
        message: '请提供目标冰箱ID'
      });
    }

    const food = await Food.moveFoodToRefrigerator(id, refrigerator_id);
    if (!food) {
      return res.status(404).json({
        success: false,
        message: '食物不存在'
      });
    }

    res.json({
      success: true,
      message: '食物移动成功',
      data: food
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '移动食物失败',
      error: error.message
    });
  }
});

// 更新食物温度状态
router.put('/:id/temperature', async (req, res) => {
  try {
    const { id } = req.params;
    const { temperature_status } = req.body;
    
    if (!temperature_status) {
      return res.status(400).json({
        success: false,
        message: '请提供温度状态'
      });
    }

    const food = await Food.updateFoodTemperature(id, temperature_status);
    if (!food) {
      return res.status(404).json({
        success: false,
        message: '食物不存在'
      });
    }

    res.json({
      success: true,
      message: '食物温度状态更新成功',
      data: food
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '更新食物温度状态失败',
      error: error.message
    });
  }
});

// 删除食物
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const success = await Food.deleteFood(id);
    
    if (!success) {
      return res.status(404).json({
        success: false,
        message: '食物不存在'
      });
    }

    res.json({
      success: true,
      message: '食物删除成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '删除食物失败',
      error: error.message
    });
  }
});

// 获取带保质期状态的所有食物
router.get('/with-shelf-life-status', async (req, res) => {
  try {
    const foods = await Food.getAllFoodsWithShelfLifeStatus();
    res.json({
      success: true,
      data: foods,
      total: foods.length
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取带保质期状态的食物失败',
      error: error.message
    });
  }
});

// 根据保质期状态获取食物
router.get('/shelf-life-status/:status', async (req, res) => {
  try {
    const { status } = req.params;
    
    // 验证保质期状态是否有效
    const validStatuses = ['normal', 'near_expiry', 'expired'];
    if (!validStatuses.includes(status)) {
      return res.status(400).json({
        success: false,
        message: `无效的保质期状态: ${status}`,
        validStatuses: validStatuses
      });
    }
    
    const foods = await Food.getFoodsByShelfLifeStatus(status);
    res.json({
      success: true,
      data: foods,
      total: foods.length,
      status: status
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '根据保质期状态获取食物失败',
      error: error.message
    });
  }
});

// 获取保质期状态统计
router.get('/stats/shelf-life', async (req, res) => {
  try {
    const stats = await Food.getShelfLifeStatusStats();
    res.json({
      success: true,
      data: stats
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取保质期状态统计失败',
      error: error.message
    });
  }
});

// 获取食物统计信息
router.get('/stats/overview', async (req, res) => {
  try {
    const stats = await Food.getFoodStats();
    res.json({
      success: true,
      data: stats
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取食物统计失败',
      error: error.message
    });
  }
});

module.exports = router;
